package com.itheima.web.controller.cargo;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.cargo.*;
import com.itheima.service.cargo.ExportProductService;
import com.itheima.service.cargo.ExportService;
import com.itheima.service.cargo.PackingService;
import com.itheima.utils.DownloadUtil;
import com.itheima.vo.PackingVo;
import com.itheima.web.controller.BaseController;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/packing")
public class ContractPackingController extends BaseController {
    @Reference
    private PackingService packingService;
    @Reference
    private ExportService exportService;
    @Reference
    private ExportProductService exportProductService;

    @RequestMapping(value = "/list", name = "装箱列表查询")
    public String list(@RequestParam(value = "page", defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "10") Integer pageSize) {

        PackingExample packingExample = new PackingExample();
        PackingExample.Criteria criteria = packingExample.createCriteria();
        criteria.andCompanyIdEqualTo(getCompanyId());

        //细粒度权限控制条件加入
        Integer degree = getLoginUser().getDegree();
        if (degree == 2) {
            criteria.andCreateDeptLike(getLoginUser().getDeptId() + "%");
        } else if (degree == 3) {
            criteria.andCreateDeptEqualTo(getLoginUser().getDeptId());
        } else if (degree == 4) {
            criteria.andCreateByEqualTo(getLoginUser().getId());
        }

        packingExample.setOrderByClause("create_time desc");//按照创建日期排序

        PageInfo pageInfo = packingService.findByPage(pageNum, pageSize, packingExample);
        List<Packing> list = packingService.findAll(packingExample);
        request.setAttribute("page", pageInfo);

        return "cargo/packing/packing-list";
    }

    @RequestMapping(value = "/toPacking", name = "跳转装箱单新增页面")
    public String toPacking(String id) {

        String[] strings = id.split(",");
        List<String> list = new ArrayList<>();
        for (int i = 0; i < strings.length; i++) {
            list.add(strings[i]);
        }
        ExportProductExample exportProductExample = new ExportProductExample();
        ExportProductExample.Criteria criteria = exportProductExample.createCriteria();
        criteria.andExportIdIn(list);
        List<ExportProduct> exportProducts = exportProductService.findAll(exportProductExample);
        Double grossWeights = 0.0;//总毛重
        Double netWeights = 0.0;//总净重
        Double volumes = 0.0;//总体积
        for (ExportProduct exportProduct : exportProducts) {
            grossWeights += exportProduct.getBoxNum() * exportProduct.getGrossWeight();
            netWeights += exportProduct.getNetWeight() * exportProduct.getBoxNum();
            volumes += exportProduct.getSizeHeight() * exportProduct.getSizeLength() * exportProduct.getSizeWidth() * exportProduct.getBoxNum();
        }
        PackingVo packingVo = new PackingVo();
        packingVo.setExportIds(id);
        packingVo.setGrossWeights(grossWeights);
        packingVo.setNetWeights(netWeights);
        packingVo.setVolumes(volumes);
        request.setAttribute("packingVo", packingVo);
        return "cargo/packing/export-toPacking";
    }

    @RequestMapping(value = "/edit", name = "装箱单新增")
    public String edit(PackingVo packingVo) {
        Packing packing = new Packing();

        ExportExample exportExample = new ExportExample();
        ExportExample.Criteria criteria = exportExample.createCriteria();
        String ids = packingVo.getExportIds();
        String[] strings = ids.split(",");
        List<String> list = new ArrayList<>();
        for (String string : strings) {
            list.add(string);
        }
        criteria.andIdIn(list);
        List<Export> exportList = exportService.findAll(exportExample);

        String consignees = "";
        String companyNames = "";
        for (int i = 0; i < exportList.size(); i++) {
            if (consignees.contains(exportList.get(i).getConsignee())) {
            } else {
                if (i == exportList.size()) {
                    consignees = consignees + exportList.get(i).getConsignee();
                } else {
                    consignees = consignees + exportList.get(i).getConsignee() + ",";
                }
            }
        }
        for (int i = 0; i < exportList.size(); i++) {
            if (companyNames.contains(exportList.get(i).getCompanyName())) {
            } else {
                if (i == exportList.size()) {
                    companyNames = companyNames + exportList.get(i).getCompanyName();
                } else {
                    companyNames = companyNames + exportList.get(i).getCompanyName() + ",";
                }
            }
        }
        packing.setPackingListId(UUID.randomUUID().toString());
        packing.setExportIds(packingVo.getExportIds());
        packing.setBuyer(consignees);
        packing.setSeller(companyNames);
        packing.setInvoiceNo(UUID.randomUUID().toString().replace("-",""));

        packing.setMarks(packingVo.getMarks());
        packing.setDescriptions(packingVo.getDescriptions());
        packing.setExportIds(packingVo.getExportIds());
        packing.setExportNos(null);
        if (packingVo.getPackingTime() != null) {
            packing.setState(1L);
            packing.setCreateTime(packingVo.getPackingTime());
            packing.setInvoiceDate(packingVo.getPackingTime());
            for (Export export : exportList) {
                System.out.println(export.toString());
                export.setState(3);
                exportService.onlyUpdateExport(export);
            }
        } else {
            packing.setState(0L);
            packing.setCreateTime(null);
        }
        packing.setCreateBy(getLoginUser().getUserName());
        packing.setCreateDept(getLoginUser().getDeptId());
        packing.setCompanyId(getCompanyId());
        packing.setCompanyName(getCompanyName());
        packingService.save(packing);
        return "redirect:/cargo/packing/list.do";
    }

    @RequestMapping(value = "/delete", name = "删除装箱单")
    public String delete(String id) {
        Packing packing = new Packing();
        packing = packingService.findById(id);
        String exportIds = packing.getExportIds();
        String[] strings = exportIds.split(",");
        List<String> list = new ArrayList<>();
        for (String string : strings) {
            list.add(string);
        }
        ExportExample exportExample = new ExportExample();
        ExportExample.Criteria criteria = exportExample.createCriteria();
        criteria.andIdIn(list);
        List<Export> exportList = exportService.findAll(exportExample);
        for (Export export : exportList) {
            export.setState(2);
            exportService.onlyUpdateExport(export);
        }
        packingService.delete(id);
        return "redirect:/cargo/packing/list.do";
    }

    String[] stringss = new String[]{};

    @RequestMapping(value = "/toUpdate", name = "跳转装箱单修改页面")
    public String toUpdate(String id) {
        Packing packing = packingService.findById(id);
        request.setAttribute("packing", packing);
        String exportIds = packing.getExportIds();
        String[] strings = exportIds.split(",");
        List<String> list = new ArrayList<>();
        for (String string : strings) {
            list.add(string);
        }
        ExportExample exportExample = new ExportExample();
        ExportExample.Criteria criteria = exportExample.createCriteria();
        criteria.andIdIn(list);
        List<Export> exportList = exportService.findAll(exportExample);
        request.setAttribute("addList", exportList);
        ExportExample exportExample1 = new ExportExample();
        ExportExample.Criteria criteria1 = exportExample1.createCriteria();
        criteria1.andStateEqualTo(2L);
        List<Export> elseList = exportService.findAll(exportExample1);
        request.setAttribute("elseList", elseList);
        for (Export export : elseList) {
            exportIds = exportIds + "," + export.getId();
        }
        stringss = exportIds.split(",");

        return "cargo/packing/packing-update";
    }

    @RequestMapping(value = "/edit1", name = "装箱单修改")
    public String edit1(Packing packing, String id) {
        Packing packing1 = packingService.findById(packing.getPackingListId());
        packing1.setMarks(packing.getMarks());

        packing1.setInvoiceDate(packing.getInvoiceDate());
        packing1.setCreateTime(packing.getInvoiceDate());
        if (packing.getInvoiceDate() != null) {
            packing1.setState(1L);
        } else {
            packing1.setState(0L);
        }


        packing1.setDescriptions(packing.getDescriptions());
        packing1.setExportNos(packing.getExportNos());
        packing1.setExportIds(id);
        packingService.update(packing1);
        ExportExample exportExample = new ExportExample();

        ExportExample.Criteria criteria = exportExample.createCriteria();
        String[] strings = id.split(",");
        List<String> list = new ArrayList<>();
        for (String string : strings) {
            list.add(string);
        }
        criteria.andIdIn(list);
        List<Export> exportList = exportService.findAll(exportExample);
        for (Export export : exportList) {
            if (export.getState() != 3) {
                export.setState(3);
                exportService.onlyUpdateExport(export);
            }
        }

        List<String> list1 = new ArrayList<>();
        for (String string : stringss) {
            list1.add(string);
        }
        ExportExample exportExample1 = new ExportExample();
        exportExample1.createCriteria().andIdIn(list1);
        List<Export> all = exportService.findAll(exportExample1);
        for (Export export : all) {
            if (!id.contains(export.getId())) {
                export.setState(2);
                exportService.onlyUpdateExport(export);
            }
        }
        return "redirect:/cargo/packing/list.do";
    }

    @RequestMapping(value = "/packingPdf", name = "pdf导出")
    public void packingPdf(String id) throws JRException, IOException {
        //1 定位出jasper文件的位置
        String realPath = session.getServletContext().getRealPath("/jasper/packing.jasper");


        //2 准备数据
        //查询单---map
        Packing packing = packingService.findById(id);
        Map<String, Object> map = BeanUtil.beanToMap(packing);

        //查询报运单下的货物----list
        String exportIds = packing.getExportIds();
        String[] strings = exportIds.split(",");
        List<String> list = new ArrayList<>();
        for (String string : strings) {
            list.add(string);
        }
        ExportExample exportExample = new ExportExample();
        exportExample.createCriteria().andIdIn(list);
        List<Export> exportList = exportService.findAll(exportExample);

        //3 填充jasper模板(jasper文件和data组装)
        JasperPrint jasperPrint = JasperFillManager.fillReport(realPath, map, new JRBeanCollectionDataSource(exportList));

        //4 输出到浏览器
        /*JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());*/
        //4 输出到浏览器
        JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());

    }

    @RequestMapping(value = "/packingPdfDownLoad", name = "pdf下载")
    public void packingPdfDownLoad(String id) throws JRException, IOException {
        //1 定位出jasper文件的位置
        String realPath = session.getServletContext().getRealPath("/jasper/packing.jasper");


        //2 准备数据
        //查询单---map
        Packing packing = packingService.findById(id);
        Map<String, Object> map = BeanUtil.beanToMap(packing);

        //查询报运单下的货物----list
        String exportIds = packing.getExportIds();
        String[] strings = exportIds.split(",");
        List<String> list = new ArrayList<>();
        for (String string : strings) {
            list.add(string);
        }
        ExportExample exportExample = new ExportExample();
        exportExample.createCriteria().andIdIn(list);
        List<Export> exportList = exportService.findAll(exportExample);

        //3 填充jasper模板(jasper文件和data组装)
        JasperPrint jasperPrint = JasperFillManager.fillReport(realPath, map, new JRBeanCollectionDataSource(exportList));


        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, stream);
        DownloadUtil.download(stream, response, "报运单.pdf");
    }
}